const cloud = require('wx-server-sdk')
cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV })
//引入SaoBeiPayClient
const SaoBeiPayClient = require('../intergration/SaoBeiPayClient');
const messageNotifyService = require('../service/messageNotifyService');
const { getSaoBeiStoreConfig } = require('../service/ConfigService');
const _ = cloud.database().command; // 数据库操作符
const { paySuccessCallback } = require('../service/paySuccessCallbackService'); // 新增

/**
 * 对账单任务服务
 * @param {Object} event 
 * @returns 
 */
async function reconOrderService(event) {
  try {
    console.log("reconOrderService start");
    const now = Date.now();
    const startTime = new Date(now - 24 * 60 * 60 * 1000); // 24小时前
    const endTime = new Date(now - 60 * 1000); // 1分钟前
    const orderQuery = await cloud.database().collection('order').where({
      create_ts: _.gte(startTime).and(_.lte(endTime)),
      order_status: '待支付'
    }).limit(200).get();
    for (const order of orderQuery.data) {
      if (!order.out_trade_no) {
        continue;
      }
      let orderInSaobei = await querySaoBeiOrderByDbOrder(order);
      let checkResult = checkOrderStatus(order, orderInSaobei);
      if (!checkResult.statusNormal) {
        // 1. 通知员工
        await messageNotifyService.notifyAbnormlOrderStautsToStaff(checkResult, order);
        // 2. 自动补单
        try {
          const payResult = await paySuccessCallback({ orderId: order.order_id });
          console.log('【reconOrderTask】自动补单成功', { orderId: order.order_id, payResult });
        } catch (err) {
          console.error('【reconOrderTask】自动补单失败', { orderId: order.order_id, err });
        }
      }
    }
    return {
      success: true,
      message: 'reconOrder service executed successfully'
    }
  } catch (error) {
    console.error('reconOrder service error:', error)
    console.error(error.stack);
    return {
      success: false,
      message: error.message || 'reconOrder service failed'
    }
  }
}
async function querySaoBeiOrderByDbOrder(dbOrder) {
  /**@type {SaoBeiPayClient} */
  let saobeiPayClient = new SaoBeiPayClient();
  const schoolCode = "xue_chang_zhi_ye";
  const productId = dbOrder.order_item?.product_id;
  console.log("准备调用getSaoBeiStoreConfig，schoolCode:", schoolCode, "productId:", productId, "type:", typeof productId);
  let saobeiStoreConfig = await getSaoBeiStoreConfig(schoolCode, productId);
  console.log("getSaoBeiStoreConfig返回:", JSON.stringify(saobeiStoreConfig));

  let saiBeiOrderReq = {};
  saiBeiOrderReq.merchant_no = saobeiStoreConfig?.merchant_no;
  saiBeiOrderReq.terminal_id = saobeiStoreConfig?.terminal_id;
  saiBeiOrderReq.key_sign = saobeiStoreConfig?.key_sign;
  saiBeiOrderReq.out_trade_no = dbOrder.out_trade_no;
  const orderInSaobei = await saobeiPayClient.queryOrder(saiBeiOrderReq);
  return orderInSaobei;
}
function checkOrderStatus(orderInDb, orderInSaobei) {
  let result = {
    statusNormal: true,
    statusErrorMsg: ""
  }
  if (orderInSaobei.trade_state == "SUCCESS") {
    result.statusNormal = false;
    result.statusErrorMsg = "扫呗订单已支付，但是订单状态为待支付";
  } else {
    result.statusNormal = true;
  }
  return result;
}

module.exports = reconOrderService 